import { useEffect, useRef, useState } from "react";
const useCountdownTimer = (initialTime: number) => {
  const [timeLeft, setTimeLeft] = useState(initialTime);
  const intervalRef = useRef<number | NodeJS.Timer | null>(null);
  // 开始倒计时
  const startCountdown = () => {
    console.log("startCountdown");
    intervalRef.current = setInterval(() => {
      setTimeLeft((timeLeft) => timeLeft - 1)
    }, 1000);
  };
  // 重新倒计时
  const resetCountdown = () => {
    console.log("resetCountdown");
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
    setTimeLeft(initialTime);
  };

  useEffect(() => {
    if (!timeLeft && intervalRef.current) {
      clearInterval(intervalRef.current);
    }
  }, [timeLeft]);
  return { timeLeft, startCountdown, resetCountdown };
};

export default useCountdownTimer;
